<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="风场" prop="windId">
        <el-select v-model="queryParams.windId" placeholder="请选择风场" @change="handleChange">
          <el-option
            v-for="item in windList"
            :key="item.id"
            :label="item.windName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="机组" prop="setId">
        <el-select v-model="queryParams.setId" placeholder="请选择机组" @change="handleSetChange">
          <el-option
            v-for="item in setList"
            :key="item.id"
            :label="item.setName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备" prop="equipmentId">
        <el-select v-model="queryParams.equipmentId" placeholder="请选择设备" @change="handleQuery">
          <el-option
            v-for="item in equipmentList"
            :key="item.id"
            :label="item.equipmentName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="故障名称" prop="faultName">
        <el-input
          v-model="queryParams.faultName"
          placeholder="请输入故障名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="故障代码" prop="faultCode">
        <el-input
          v-model="queryParams.faultCode"
          placeholder="请输入故障代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:fault:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:fault:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:fault:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:fault:export']"
        >导出
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="faultList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="id" width="50"/>
      <el-table-column label="故障名称" align="center" prop="faultName"/>

      <el-table-column label="故障分类" align="center" prop="faultType">
        <template slot-scope="scope">
          <div v-if="scope.row.faultType === '1'">
            <el-tag
              type="info"
              disable-transitions>机械故障
            </el-tag>
          </div>
          <div v-else-if="scope.row.faultType === '2'">
            <el-tag
              type="success"
              disable-transitions>电气故障
            </el-tag>
          </div>
          <div v-else-if="scope.row.faultType === '3'">
            <el-tag
              type="danger"
              disable-transitions>环境故障
            </el-tag>
          </div>
          <div v-else-if="scope.row.faultType === '4'">
            <el-tag
              type="warning"
              disable-transitions>软件故障
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="故障代码" align="center" prop="faultCode"/>
      <el-table-column label="故障描述" align="center" prop="faultContent"/>
      <el-table-column label="故障报出时间" align="center" prop="faultDate" width="80">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.faultDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始处理时间" align="center" prop="dealDate" width="80">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dealDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维护停机时间" align="center" prop="stopDate"/>
      <el-table-column label="复位运行时间" align="center" prop="operateDate"/>
      <el-table-column label="故障位置一级" align="center" prop="position1"/>
      <el-table-column label="故障位置二级" align="center" prop="position2"/>
      <el-table-column label="故障位置三级" align="center" prop="position3"/>
      <el-table-column label="排查项目" align="center" prop="checkItem"/>
      <el-table-column label="故障原因" align="center" prop="faultReason"/>
      <el-table-column label="负责人" align="center" prop="header"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:fault:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:fault:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-generate"
            @click="handleInitChart(scope.row)"
          >生成饼状图
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="pieChartTitle" :visible.sync="isshowPie" width="800px" append-to-body>
      <div id="pieChart" style="height: 600px"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPie">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改故障管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="风场" prop="windId">
              <el-select v-model="form.windId" placeholder="请选择风场" style="width: 100%" @change="handleChange">
                <el-option
                  v-for="item in windList"
                  :key="item.id"
                  :label="item.windName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机组" prop="setId">
              <el-select v-model="form.setId" placeholder="请选择机组" @change="handleSetChange" style="width: 100%">
                <el-option
                  v-for="item in setList"
                  :key="item.id"
                  :label="item.setName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备" prop="equipmentId">
              <el-select v-model="form.equipmentId" placeholder="请选择设备" style="width: 100%">
                <el-option
                  v-for="item in equipmentList"
                  :key="item.id"
                  :label="item.equipmentName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障名称" prop="faultName">
              <el-input v-model="form.faultName" placeholder="请输入故障名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障代码" prop="faultCode">
              <el-input v-model="form.faultCode" placeholder="请输入故障代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障分类" prop="faultType">
              <el-select v-model="form.faultType" placeholder="请选择故障分类" style="width: 100%">
                <el-option value="1"  label="机械故障"
                >机械故障
                </el-option>
                <el-option value="2" label="电器故障"
                >电器故障
                </el-option>
                <el-option value="3" label="环境故障"
                >环境故障
                </el-option>
                <el-option value="4" label="软件故障"
                >软件故障
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="header">
              <el-input v-model="form.header" placeholder="请输入负责人"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="故障报出时间" prop="faultDate">
              <el-date-picker clearable
                              v-model="form.faultDate"
                              type="date" style="width: 100%"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择故障报出时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始处理时间" prop="dealDate">
              <el-date-picker clearable
                              v-model="form.dealDate"
                              type="date" style="width: 100%"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择开始处理时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护停机时间" prop="stopDate">
              <el-input v-model="form.stopDate" placeholder="请输入维护停机时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="复位运行时间" prop="operateDate">
              <el-input v-model="form.operateDate" placeholder="请输入复位运行时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障位置一级" prop="position1">
              <el-input v-model="form.position1" placeholder="请输入故障位置一级"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障位置二级" prop="position2">
              <el-input v-model="form.position2" placeholder="请输入故障位置二级"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障位置三级" prop="position3">
              <el-input v-model="form.position3" placeholder="请输入故障位置三级"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排查项目" prop="checkItem">
              <el-input v-model="form.checkItem" placeholder="请输入排查项目"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障原因" prop="faultReason">
              <el-input v-model="form.faultReason" placeholder="请输入故障原因"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障描述">
              <editor v-model="form.faultContent" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-divider content-position="center">维修管理信息</el-divider>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSysRepairs">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSysRepairs">删除</el-button>
            </el-col>
          </el-row>
          <el-table :data="sysRepairsList" :row-class-name="rowSysRepairsIndex"
                    @selection-change="handleSysRepairsSelectionChange" ref="sysRepairs">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column label="维修等级" prop="repairsLevel" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.repairsLevel" placeholder="请输入维修等级"/>
              </template>
            </el-table-column>
            <el-table-column label="维修类别" prop="repairsType" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.repairsType" placeholder="请输入维修类别"/>
              </template>
            </el-table-column>
            <el-table-column label="工作票编号" prop="ticketNumber" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.ticketNumber" placeholder="请输入工作票编号"/>
              </template>
            </el-table-column>
            <el-table-column label="维修动作" prop="repairsAction" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.repairsAction" placeholder="请输入维修动作"/>
              </template>
            </el-table-column>
            <el-table-column label="维修时间" prop="repairsTime" width="240">
              <template slot-scope="scope">
                <el-date-picker clearable v-model="scope.row.repairsTime" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择维修时间"/>
              </template>
            </el-table-column>
            <el-table-column label="下次维修时间" prop="nextRepairsTime" width="240">
              <template slot-scope="scope">
                <el-date-picker clearable v-model="scope.row.nextRepairsTime" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择下次维修时间"/>
              </template>
            </el-table-column>
            <el-table-column label="维修费用" prop="repairsFee" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.repairsFee" placeholder="请输入维修费用"/>
              </template>
            </el-table-column>
            <el-table-column label="风场" prop="windId" width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.windId" placeholder="请选择风场" @change="handleChange">
                  <el-option
                    v-for="item in windList"
                    :key="item.id"
                    :label="item.windName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="机组" prop="setId" width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.setId" placeholder="请选择机组" @change="handleSetChange">
                  <el-option
                    v-for="item in setList"
                    :key="item.id"
                    :label="item.setName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="设备" prop="equipmentId" width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.equipmentId" placeholder="请选择设备">
                  <el-option
                    v-for="item in equipmentList"
                    :key="item.id"
                    :label="item.equipmentName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="维修员" prop="repairsPerson" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.repairsPerson" placeholder="请输入维修员"/>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listFault, getFault, delFault, addFault, updateFault, submmitFault} from "@/api/system/fault";
import {listWind} from "@/api/system/wind";
import {listSet} from "@/api/system/set";
import {getEquipment, listEquipment} from "@/api/system/equipment";
import * as echarts from "echarts";

export default {
  name: "Fault",
  data() {
    return {
      pieChartData: [],
      chart: null,
      windList: [],
      windId: '',
      setList: [],
      setId: '',
      equipment: {},
      equipmentList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSysRepairs: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 故障管理表格数据
      faultList: [],
      // 维修管理表格数据
      sysRepairsList: [],
      // 弹出层标题
      title: "",
      pieChartTitle: '故障饼状图',
      // 是否显示弹出层
      open: false,
      //是否显示饼状图弹出层
      isshowPie: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        windId: null,
        setId: null,
        equipmentId: null,
        faultName: null,
        faultCode: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        windId: [
          {required: true, message: "风场不能为空", trigger: "blur"}
        ],
        setId: [
          {required: true, message: "机组不能为空", trigger: "blur"}
        ],
        equipmentId: [
          {required: true, message: "设备不能为空", trigger: "blur"}
        ],
        faultName: [
          {required: true, message: "故障名称不能为空", trigger: "blur"}
        ],
        faultCode: [
          {required: true, message: "故障代码不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getWindList();
    this.getSetList();
    this.getEquipmentList()
  },
  methods: {
    handleChange(val) {
      console.log(val)
      this.windId = val;
      this.getSetList()
    },
    handleSetChange(val) {
      console.log(val)
      this.setId = val;
      this.getEquipmentList()
    },
    getWindList() {
      listWind({
        pageNum: 1,
        pageSize: 10000
      }).then(response => {
        this.windList = response.rows;
      });
    },
    getSetList() {
      listSet({
        pageNum: 1,
        pageSize: 10000,
        setName: null,
        windId: this.windId
      }).then(response => {
        this.setList = response.rows;
      });
    },
    getEquipmentList() {
      listEquipment({
        pageNum: 1,
        pageSize: 10000,
        setId: this.setId,
        windId: this.windId
      }).then(response => {
        this.equipmentList = response.rows;
      });
    },
    /** 查询故障管理列表 */
    getList() {
      this.loading = true;
      listFault(this.queryParams).then(response => {
        this.faultList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleInitChart(row) {
      this.pieChartData = []
      this.isshowPie = true
      console.log(row)
      getEquipment(row.equipmentId).then(response => {
        console.log(response.data)
        this.equipment = response.data;
        if (this.equipment.equipmentName == '发电机' || this.equipment.equipmentName == '变流器') {
          this.pieChartData.push({
            name: '机械故障',
            value: 10
          })
          this.pieChartData.push({
            name: '电器故障',
            value: 70
          })
          this.pieChartData.push({
            name: '环境故障',
            value: 10
          })
          this.pieChartData.push({
            name: '软件故障',
            value: 10
          })
        } else {
          this.pieChartData.push({
            name: '机械故障',
            value: 70
          })
          this.pieChartData.push({
            name: '电器故障',
            value: 10
          })
          this.pieChartData.push({
            name: '环境故障',
            value: 10
          })
          this.pieChartData.push({
            name: '软件故障',
            value: 10
          })
        }
        this.chart = echarts.init(document.getElementById('pieChart'))
        this.chart.setOption({
          color: ['#A4B6C9', '#1ab394', '#f80013', '#409eff'],
          tooltip: {
            trigger: 'item',
            formatter: '{b}({d}%)'
          },
          legend: {
            left: 'center',
            bottom: '20',
            data: ['机械故障', '电器故障', '环境故障', '软件故障']
          },
          series: [
            {
              name: '各类故障占比',
              type: 'pie',
              radius: [15, 95],
              center: ['50%', '38%'],
              data: this.pieChartData
            }
          ],
        })
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消饼状图按钮
    cancelPie() {
      this.isshowPie = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        windId: null,
        setId: null,
        equipmentId: null,
        faultName: null,
        faultType: null,
        faultCode: null,
        header: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.sysRepairsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加故障管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFault(id).then(response => {
        this.form = response.data;
        this.sysRepairsList = response.data.sysRepairsList;
        this.open = true;
        this.title = "修改故障管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.sysRepairsList = this.sysRepairsList;
          if (this.form.id != null) {
            updateFault(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFault(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除故障管理编号为"' + ids + '"的数据项？').then(function () {
        return delFault(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 维修管理序号 */
    rowSysRepairsIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 维修管理添加按钮操作 */
    handleAddSysRepairs() {
      let obj = {};
      obj.repairsLevel = "";
      obj.repairsType = "";
      obj.ticketNumber = "";
      obj.repairsAction = "";
      obj.repairsTime = "";
      obj.nextRepairsTime = "";
      obj.repairsFee = "";
      obj.spareParts = "";
      obj.repairsResult = "";
      obj.windId = "";
      obj.setId = "";
      obj.equipmentId = "";
      obj.remark = "";
      obj.repairsPerson = "";
      this.sysRepairsList.push(obj);
    },
    /** 维修管理删除按钮操作 */
    handleDeleteSysRepairs() {
      if (this.checkedSysRepairs.length == 0) {
        this.$modal.msgError("请先选择要删除的维修管理数据");
      } else {
        const sysRepairsList = this.sysRepairsList;
        const checkedSysRepairs = this.checkedSysRepairs;
        this.sysRepairsList = sysRepairsList.filter(function (item) {
          return checkedSysRepairs.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSysRepairsSelectionChange(selection) {
      this.checkedSysRepairs = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/fault/export', {
        ...this.queryParams
      }, `fault_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
